window.tinymce.PluginManager.add('selected', function (editor) {

  // 将复选框选中和不选中图片url转为base64
  let checkIcon  = ''; //选中复选框图标
  let unCheckIcon  = '';//未选中复选框图标
  let defaultSize = "18px";
  function imeBase64(img) {
    let canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    let ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    let ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
    let dataURL = canvas.toDataURL("image/"+ext);
    return dataURL;
  }
  function getImgBase64(img) {
  //因为要等元素加载完之后再获取url，所以返回promise实例，通过promise.then() 来获取转换后的图片url
      return new Promise((resolve, reject) => {
          let image = new Image();
          image.src = img;
          image.onload = function(){
              var base64 = imeBase64(image);
              resolve(base64);
          }
          image.onerror = reject;
      })
  }
  getImgBase64('./tinymce/plugins/selected/img/selected.png').then(res => {
    checkIcon = res;
  }).catch((e) => {
    console.log(e);
  });
  getImgBase64('./tinymce/plugins/selected/img/unselected.png').then(res => {
    unCheckIcon = res;
  }).catch((e) => {
    console.log( e);
  });
    
  //自定义工具栏按钮：icon：selected使用tinymce自带[可用图标](https://www.tiny.cloud/docs/advanced/editor-icon-identifiers/)
  editor.ui.registry.addButton('selected', {
    icon: 'selected',
    tooltip: '复选框',
    onAction: function () {
    //创建新元素create(name:String, attrs:Object, html:String):Element
    //html字符串中是空格字符串，避免当复选框前后字符时打印不显示
    //tinymce文本p标签。选p、div标签不能被包含在p标签中。所以选ins标签，要设置复选框的大小，只能将元素设为行内块元素 inline-block。设为块元素会换行。
      let el = editor.dom.create('ins', {
          'class': 'icon-checkbox',
          'contenteditable': false,
          'style': `display: inline-block; vertical-align: middle; outline: none; width: ${defaultSize}; height:${defaultSize};background: url('${unCheckIcon}') no-repeat; background-size:100%;`
      }, " "); 
      //获取选中的元素节点
      let node = editor.selection.getNode(); 
      //判断有节点被选中，且被选中节点是否是复选框。是则将新复选框替换该复选框。否则插入新复选框节点。
      if(node&&(node.getAttribute("class") == 'icon-checkbox' || node.getAttribute("class") == 'checkbox-checked')) {
          editor.dom.replace(el, node, false);
          //editor.nodeChanged();触发节点已变化的事件，需要在富文本初始化时定义editor.on("NodeChange", function(){})事件，将插入后的最新富文本内容返回父组件，及时更新打印的html。
          editor.nodeChanged();
      } else {
          editor.selection.setNode(el);
          editor.nodeChanged();
      }
    },
  });
        
  editor.on('click', function (e) {
    e.stopPropagation();
    e.preventDefault();
    let node = editor.dom.get(e.target);
    let activeSize = node.offsetWidth > 0 ? node.offsetWidth + 'px' : defaultSize; 
    //如果节点是未选中的复选框，则将节点替换成已选中的。
    if(node&&node.getAttribute("class") == 'icon-checkbox') {
      let el = editor.dom.create('ins', {
          'class': 'checkbox-checked',
          'contenteditable': false,
          'style': `display: inline-block; vertical-align: middle; outline: none; width: ${activeSize}; height:${activeSize};background: url('${checkIcon}') no-repeat; background-size:100%;`
      }, " ");
      editor.dom.replace(el, node, false);
      editor.nodeChanged();
    } else if (node && node.getAttribute("class") == 'checkbox-checked') {
      let el = editor.dom.create('ins', {
          'class': 'icon-checkbox',
          'contenteditable': false,
          'style': `display: inline-block; vertical-align: middle; outline: none; width: ${activeSize}; height:${activeSize};background: url('${unCheckIcon}') no-repeat; background-size:100%;`
      }, " ");
      editor.dom.replace(el, node, false);
      editor.nodeChanged();
    }
  })

  // 在向用户显示的菜单中，部分由分隔符分隔。Sections 可以返回一个空的菜单项数组，以指示该部分没有适用于当前上下文的项目，不应显示。
  let iconSizes = ['18px', '20px', '24px', '28px', '32px']; //设置复选框大小的可选尺寸
  editor.ui.registry.addContextMenu('selected', { //name: selected 在初始化配置contextmenu的时候使用
    update: function (element) {
        return (element.getAttribute("class") == 'icon-checkbox' || element.getAttribute("class") == 'checkbox-checked')?iconSizes:'';
    }
  });

  iconSizes.forEach(item => { //循环尺寸数组自定义相应的按钮
    editor.ui.registry.addMenuItem(item, {
      text: item,
      onAction: function () {
        let node = editor.selection.getNode();
        if(node&&node.getAttribute("class") == 'icon-checkbox') {
          let el = editor.dom.create('ins', {
              'class': 'icon-checkbox',
              'contenteditable': false,
              'style': `display: inline-block; vertical-align: middle; outline: none; width: ${item}; height:${item};background: url('${unCheckIcon}') no-repeat; background-size:100%;`
          }, " ");
          editor.dom.replace(el, node, false);
          editor.nodeChanged();//触发节点更改事件更新绑定值

        } else if (node && node.getAttribute("class") == 'checkbox-checked') {
          let el = editor.dom.create('ins', {
              'class': 'checkbox-checked',
              'contenteditable': false,
              'style': `display: inline-block; vertical-align: middle; outline: none; width: ${item}; height:${item};background: url('${checkIcon}') no-repeat; background-size:100%;`
          }, " ");
          editor.dom.replace(el, node, false);
          editor.nodeChanged();
        }
      },
    });
  })
});
